<?php

namespace app\admin\controller\pro;

use app\admin\model\Storepro;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 加光
 *
 * @icon fa fa-circle-o
 */
class Light extends Backend
{

    /**
     * Light模型对象
     * @var \app\admin\model\pro\Light
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\pro\Light;
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        $list = $this->getXXX($list);

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }



    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);

            // $diaobo = $this->test_diaobo1($params['zhongtu_update']);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    // 测试调拨1:   曾祖代厂-后备兔库(x厂)  转    在产种兔库(选择厂)
    // @demo
    public function test_diaobo1(){
        $zhongtu_num = 500 ;
        $factory_id = 1 ;
        $factory_in_store = 1 ;

        // 1  曾祖代厂-后备兔库   调出
        // 查   曾祖代厂-后备兔库(x厂)   的库信息;   一般一个归属库= 一个创建的库
        $storem1 = Db::name("storem1")
            ->where("factory_id", 3)        // todo  这里逻辑定死了在这个库调出, 应该预设,并可选
            ->where("storea_id", 5)         // todo
            ->order("id DESC")
            ->find();

        $storem1_in = Db::name("storem1")
            ->where("factory_id", $factory_id)        // todo  这里逻辑定死了在这个库调出, 应该预设,并可选
            ->where("storea_id", $factory_in_store )             // todo
            ->order("id DESC")
            ->find();

        $data_out = [
            'factory_id' => $storem1['factory_id'],
            'storesub_id' => $storem1['storesub_id'],
            'store1_id' => $storem1['store1_id'],
            'storea_id' => $storem1['storea_id'],
            'storem1_id' => $storem1['id'],
            'cal' => '出库',
            'num' => $zhongtu_num,
            'field1' => '生产调拨',
            'status' => 'normal',
            'createtime' => date("Y-m-d H:i:s")
        ];

        //  2  本厂-在产种兔库   调入
        $data_in = [
            'factory_id' => $storem1_in['factory_id'],
            'storesub_id' => $storem1_in['storesub_id'],
            'store1_id' => $storem1_in['store1_id'],
            'storea_id' => $storem1_in['storea_id'],
            'storem1_id' => $storem1_in['id'],
            'cal' => '入库',
            'num' => $zhongtu_num,
            'field1' => '生产调拨',
            'status' => 'normal',
            'createtime' => date("Y-m-d H:i:s")
        ];

        $re['out'] = Db::name("storepro")->insert($data_out);
        $re['in'] = Db::name("storepro")->insert($data_in);

        return $re;
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }



}
